import { FormCard } from '@components/FormCard'
import { useFormCallback } from '@hooks/useFormCallback'
import { useHonorCreateMutation, useHonorUpdateMutation } from '@services/honor'
import { Link } from '@tanstack/react-router'
import { Breadcrumb, Button, Form, Input, InputNumber, Switch } from 'antd'
import dayjs from 'dayjs'
import { useEffect, useState } from 'react'
import ImagePreview from './ImagePreview'

export function FormHonor({ defaultData }) {
  const [form] = Form.useForm()
  const [data, setData] = useState(defaultData)
  const { mutate } = defaultData.id ? useHonorUpdateMutation() : useHonorCreateMutation()
  const { onFinish, onFailed } = useFormCallback(mutate, {
    handle: (values) => {
      return { ...values, ...(defaultData.id && { id: defaultData.id }) }
    },
  })

  useEffect(() => {
    form.setFieldsValue({ ...data, published_at: dayjs(data.published_at) })
  }, [])

  const card = {
    title: (
      <Breadcrumb
        items={[
          { title: '关于我们' },
          { title: <Link to={'..'}>企业荣誉</Link> },
          { title: defaultData.id ? '编辑' : '新增' },
        ]}
      />
    ),
  }

  return (
    <FormCard card={card}>
      <Form
        name="form-honor"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        style={{ maxWidth: '100%' }}
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFailed}
        autoComplete="off">
        <Form.Item
          label="证书名称"
          name="name"
          rules={[{ required: true, message: '请输入标题' }]}>
          <Input />
        </Form.Item>
        <Form.Item
          label="荣誉证书"
          name="image"
          rules={[{ required: true, message: '请上传封面图!' }]}>
          <ImagePreview
            key="image"
            aspect="4:3"
            url={data.image}
            onChange={(resp) => {
              setData({ ...data, image: resp.url })
              form.setFieldsValue({ image: resp.url })
            }}
          />
        </Form.Item>

        <Form.Item label="排　　序" name="orderby" width={'206px'}>
          <InputNumber className="w-[206px]!" min={0} />
        </Form.Item>

        <Form.Item label="是否隐藏" name="hide">
          <Switch checkedChildren="隐藏" unCheckedChildren="显示" />
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            保 存
          </Button>
        </Form.Item>
      </Form>
    </FormCard>
  )
}
